# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>
import logging
from excavator.utils.shell import c_run_cmd
from excavator.utils.file import read_key_value_file
from excavator.utils.output import ExcavatorJobOutput
from excavator.job.base import Job
from excavator.models.selinux import SELinuxConfig
from excavator.models.report import notify_info, notify_err
from excavator.group.harvests import HarvestsGroup

logger = logging.getLogger("excavator.job")

selinux_config = "/etc/selinux/config"
selinux_status_get_cmd = "/usr/sbin/getenforce"
selinux_status_set_cmd = "/usr/sbin/setenforce"


def _get_persistence_selinux_config():
    try:
        data = read_key_value_file(selinux_config)
        status = data["SELINUX"]
        return None, status
    except Exception as e:
        return e, ""


class HarvestsSELinuxConfig(Job):
    group = HarvestsGroup
    requires = ()
    provides = (SELinuxConfig,)

    def run(self, *args, **kwargs):
        ExcavatorJobOutput.info(self.name, "harvests selinux config")
        logger.info("get runtime selinux config")
        # get runtime selinux config
        ret, runtime_config = c_run_cmd(selinux_status_get_cmd)
        if ret != 0:
            msg = "get selinux config failed: {}".format(runtime_config)
            logger.error(msg)
            notify_err(msg, self.name)
        notify_info("get runtime selinux config", self.name)
        # get persistence selinux config
        logger.info("get persistence selinux config")
        err, persistence_config = _get_persistence_selinux_config()
        if err is not None:
            logger.error(err)
            notify_err(err, self.name)
        notify_info("get persistence selinux config success", self.name)
        SELinuxConfig.create(runtime_config=runtime_config.strip(), persistence_config=persistence_config)
